import axios from "axios";
import localCahce from "@/utils/cache";
class Request {
  constructor(config) {
    this.instance = axios.create(config);
    //this.interceptors = config.interceptors;

    //自定义拦截器
    //this.interceptors.request.use(
    //  this.interceptors.requestInterceptors,
    //  this.interceptors.requestInterceptorsCatch
    //);
    //this.interceptors.response.use(
    //  this.interceptors.responseInterceptors,
    //  this.interceptors.responseInterceptorsCatch
    //);

    //全局拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = localCahce.getItem("token");
        if (token) config.headers.Authorization = `Bearer ${token}`;
        return config;
      },
      (err) => {
        return err;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        return res.data;
      },
      (err) => {
        return err;
      }
    );
  }

  request(config) {
    return new Promise((resolve, reject) => {
      //if (config.interceptors.requestInterceptors) {
      //  config = config.interceptors.requestInterceptors(config);
      //}

      this.instance
        .request(config)
        .then((res) => {
          //if (config.interceptors.responseInterceptors) {
          //  res = config.interceptors.responseInterceptors(res);
          //}
          resolve(res);
        })
        .catch((err) => {
          reject(err);
          return err;
        });
    });
  }

  get(config) {
    return this.request({ ...config, method: "GET" });
  }

  post(config) {
    return this.request({ ...config, method: "POST" });
  }

  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }

  put(config) {
    return this.request({ ...config, method: "PUT" });
  }

  patch(config) {
    return this.request({ ...config, method: "PATCH" });
  }
}

export default Request;
